'use strict'
import service from './request'
import bus from './bus.js'
import store from '@/store'
import { getToken, getRefreshToken } from '@/utils/auth'
// import { default as expiresCalculation, getExpiresTime } from './expires'
import { refreshToken } from 'api/api.js'
// import router from '@/router'

const API_URL = window.g.API_ROOT
const API_URL_JWT = window.g.API_ROOT_JWT
const API_URL_RIS = window.g.API_ROOT_RIS
const API_URL_STATISTICS = window.g.API_ROOT_STATISTICS

// 请求参数
function getOptions(args) {
  // getOptions({baseURL, url, method, data, query, queryAndBody})
  const { baseURL, url = '', method = 'post', data = {}, query = null, queryAndBody = null, isPic = false } = args
  let options = {
    method: method,
    baseURL: baseURL || API_URL,
    url: url,
    timeout: window.g.AXIOS_TIMEOUT ? window.g.AXIOS_TIMEOUT : 10000,
    headers: {}
  }
  if (isPic) {
    options.responseType = 'arraybuffer'
  }
  if (queryAndBody) {
    options.headers['Content-Type'] = isPic? 'image/png' : 'application/json;charset=UTF-8'
    options.params = data.params
    options.data = data.body
  } else {
    const pd = !query ? 'data' : 'params'
    options[pd] = data
  }

  return options
}
// 二进制流转换为base64 格式。
function getBase64(data) {
  return new Promise((resolve, reject) => {
    const blob = new Blob([data], { type: "image/png" }); // 必须指定type类型
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

async function checkStatus(response, isPic = false) {
  // console.log('进入checkStatus', response)
  // 处理响应数据
  if (response && response.status === 200) {
    // loading,如果http状态码正常，则直接返回数据
    let res = response.data
    if (!res) {
      showMessage('error','服务器开了个小差')
      return false
    }
    // console.log('checkStatus=>isPic', isPic)
    isPic && console.log('checkStatus=>res', res)
    if (isPic) {
      console.log('二进制流转化')
      // 传入二进制
      const base64 = await getBase64(res)
      console.log('转化结果', base64)
      return base64
    }
    if (res.code === 10000 || res.Code === 10000 || res.Code === 200 || res.code === 1 || res.code === 0 || res.code === 400) {
      return res
    }
    if (res.code === 10001) {
      // console.log('10001', res.message)
      if (res.message !== '当前用户为超级管理员,默认拥有所有数据权限') {
        showMessage('error', res.message)
        return
      }
      return res
    } else {
      if (res.Message) {
        showMessage('error', res.Message)
      }else if (res.message) {
        showMessage('error', res.message)
      }
      return false
    }
  } else if (response.status === 400) {
    if (response.data && response.data.message) {
      showMessage('error',`${response.data.message}`)
    }
    return response
  }  else if (response.status === 401) {
    // 401属于没权限，或者token已经过期，跳到首页让重新登录即可
    bus.$emit('toLoginPage')
  } else {
    if (response.data && response.data.Message) {
        showMessage('error',response.data.Message)
    } else if (response.data && response.data.message) {
        showMessage('error',response.data.message)
    }
    return false
  }
}

// 令牌时间过期后的刷新令牌方法
export function postRefreshToken() {
  // 如果有这个字段 去刷新token
  let token = getToken()
  // console.log('postRefreshToken_token', token)
  let refreshTokenStr = getRefreshToken() // 刷新令牌
  // console.log('refreshTokenStr', refreshTokenStr)
  return new Promise(async (resolve) => {
    if (!token || !refreshTokenStr) {
      // 如果token不存在
      resolve(false)
    } else {
      let data = {
        accessToken: token,
        refreshToken: refreshTokenStr
      }
      await refreshToken(data).then(async (res) => {
        if (res) {
          const cont = res.content
          await store.dispatch('user/setNewTokenInfo', cont)
          // 重新调用接口
          resolve(true)
        } else {
          resolve(false)
        }
      }).catch(error => {
        resolve(false)
      })
    }
  })
}

function checkCode(error) {
  // console.log('checkCode', error)
  showMessage('error', error && typeof error !== 'object' ? error : '网络异常~')
  return error
}

function showMessage(type, msg){
  // console.log('进入showMessage,打印msg', msg)
  if(type === 'error'){
    bus.$message.error(msg)
  }else{
    bus.$message.warning(msg)
  }
}

const reService = (data) => {
  const options = getOptions(data)
  return service(options)
  .then(response => {
    return checkStatus(response || {
      status: 10001,
      message: '接口请求异常'
    }, data.isPic)
  })
  .catch(res => {
    // console.log('网络异常？res', res)
    return checkCode(res || {
      status: 10001,
      message: '接口请求异常'
    })
  })
}

const reServiceDelete = (data) => {
  const options = getOptions(data)
  return serviceDelete(options)
  .then(response => {
    return checkStatus(response || {
      status: 10001,
      message: '接口请求异常'
    }, data.isPic)
  })
  .catch(res => {
    // console.log('网络异常？res', res)
    return checkCode(res || {
      status: 10001,
      message: '接口请求异常'
    })
  })
}

export default {
  deleteRIS(url, data, queryAndBody) {
    // delete请求方式
    return reService({
      baseURL: API_URL_RIS,
      url,
      method: 'delete',
      data,
      query: 'query',
      isPic: true,
      queryAndBody
    })
  },
  getRIS(url, data, query) {
    // post请求方式
    return reService({
      baseURL: API_URL_RIS,
      url,
      method: 'get',
      data,
      query,
      isPic: true
    }, true)
  },
  postRIS(url, data, query, queryAndBody) {
    // post请求方式
    return reService({
      baseURL: API_URL_RIS,
      url,
      data,
      query,
      queryAndBody
    })
  },
  postJWT(url, data, query, queryAndBody) {
    // post请求方式
    return reService({
      baseURL: API_URL_JWT,
      url,
      data,
      query,
      queryAndBody
    })
  },
  getJWT(url, data, query) {
    // get请求方式
    return reService({
      baseURL: API_URL_JWT,
      url,
      method: 'get',
      data,
      query
    })
  },
  putJWT(url, data, query, queryAndBody) {
    // put请求方式
    return reService({
      baseURL: API_URL_JWT,
      url,
      method: 'put',
      data,
      query,
      queryAndBody
    })
  },
  post(url, data, query, queryAndBody) {
    // post请求方式
    return reService({
      url,
      data,
      query,
      queryAndBody
    })
  },
  get(url, data, query) {
    // get请求方式
    return reService({
      url,
      method: 'get',
      data,
      query
    })
  },
  put(url, data, query, queryAndBody) {
    // put请求方式
    return reService({
      url,
      method: 'put',
      data,
      query,
      queryAndBody
    })
  },
  patch(url, data, query) {
    // put请求方式
    return reService({
      url,
      method: 'patch',
      data,
      query
    })
  },
  delete(url, data) {
    // delete请求方式
    return reService({
      url,
      method: 'delete',
      data,
      query: 'query'
    })
  },
  getOther(url, data, query) {
    // get请求方式
    return reService({
      baseURL: API_URL_STATISTICS,
      url,
      method: 'get',
      data,
      query
    })
  },
  postSchedule(url, data, query, queryAndBody) {
    // post请求方式 （API_ROOT_SCHEDULE，接口返回，或配置文件配置)
    return reService({
      baseURL: window.g.API_ROOT_SCHEDULE,
      url,
      data,
      query,
      queryAndBody
    })
  },
}
